package org.jeecg.modules.ncmeapis.network.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.swagger.BusinessApi;
import org.jeecg.modules.ncmeapis.network.entities.entity.NetworkPath;
import org.jeecg.modules.ncmeapis.network.entities.entity.vo.PathWithPerm;
import org.jeecg.modules.ncmeapis.network.enums.FileSource;
import org.jeecg.modules.ncmeapis.network.service.INetworkPathService;
import org.jeecg.modules.ncmeapis.network.service.INetworkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 文件目录
 */
@Api(tags = "文件管理-目录操作(jeecg)")
@RestController
@BusinessApi
@RequestMapping("/network/networkPath")
@Slf4j
class NetworkPathController extends JeecgController<NetworkPath, INetworkPathService> {
    @Autowired
    private INetworkPathService networkPathService;
    @Autowired
    private INetworkService networkService;

    /**
     * 分页列表查询
     */
    //@AutoLog(value = "文件目录-分页列表查询")
//    @ApiOperation(value = "文件目录-分页列表查询", notes = "文件目录-分页列表查询")
    @GetMapping(value = "/rootList")
    public Result<IPage<NetworkPath>> queryPageList(NetworkPath networkPath,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            QueryWrapper<NetworkPath> queryWrapper = QueryGenerator.initQueryWrapper(networkPath, req.getParameterMap());
            List<NetworkPath> list = networkPathService.queryTreeListNoPage(queryWrapper);
            IPage<NetworkPath> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } else {
            String parentId = networkPath.getPid();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            networkPath.setPid(null);
            QueryWrapper<NetworkPath> queryWrapper = QueryGenerator.initQueryWrapper(networkPath, req.getParameterMap());
            // 使用 eq 防止模糊查询
            queryWrapper.eq("pid", parentId);
            Page<NetworkPath> page = new Page<NetworkPath>(pageNo, pageSize);
            IPage<NetworkPath> pageList = networkPathService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
    }

    /**
     * 【vue3专用】加载节点的子数据
     */
    @RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
    public Result<List<SelectTreeModel>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
        Result<List<SelectTreeModel>> result = new Result<>();
        try {
            List<SelectTreeModel> ls = networkPathService.queryListByPid(pid);
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 【vue3专用】加载一级节点/如果是同步 则所有数据
     */
    @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
    public Result<List<SelectTreeModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
        Result<List<SelectTreeModel>> result = new Result<>();
        try {
            List<SelectTreeModel> ls = networkPathService.queryListByCode(pcode);
            if (!async) {
                loadAllChildren(ls);
            }
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 【vue3专用】递归求子节点 同步加载用到
     */
    private void loadAllChildren(List<SelectTreeModel> ls) {
        for (SelectTreeModel tsm : ls) {
            List<SelectTreeModel> temp = networkPathService.queryListByPid(tsm.getKey());
            if (temp != null && temp.size() > 0) {
                tsm.setChildren(temp);
                loadAllChildren(temp);
            }
        }
    }

    //@AutoLog(value = "文件目录-获取子数据")
//    @ApiOperation(value = "文件目录-获取子数据", notes = "文件目录-获取子数据")
    @GetMapping(value = "/childList")
    public Result<IPage<NetworkPath>> queryPageList(NetworkPath networkPath, HttpServletRequest req) {
        QueryWrapper<NetworkPath> queryWrapper = QueryGenerator.initQueryWrapper(networkPath, req.getParameterMap());
        List<NetworkPath> list = networkPathService.list(queryWrapper);
        IPage<NetworkPath> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
        return Result.OK(pageList);
    }

    //@AutoLog(value = "文件目录-批量获取子数据")
//    @ApiOperation(value = "文件目录-批量获取子数据", notes = "文件目录-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<NetworkPath> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<NetworkPath> list = networkPathService.list(queryWrapper);
            IPage<NetworkPath> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }

    @AutoLog(value = "文件目录-添加")
    @ApiOperation(value = "文件目录-添加", notes = "文件目录-添加")
    @RequiresPermissions("network:network_path:add")
    @PostMapping(value = "/add")
    public Result<String> add(@Validated @RequestBody NetworkPath networkPath) {
        if (StringUtils.isEmpty(networkPath.getName()) && StringUtils.isEmpty(networkPath.getFileUrl())) {
            return Result.error(networkPath.getType().equals("file") ? "文件路径不能为空" : "文件夹名称不能为空");
        }
        //判断文件重名
        networkService.checkNameRepeats(networkPath.getPid(), networkPath.getName(), networkPath.getType());
        if (StringUtils.isEmpty(networkPath.getFileUrl())) {
            networkService.mkdir(networkPath.getName(), networkPath.getPid());
            return Result.OK("新建文件夹成功");
        } else {
            networkService.upload(networkPath.getPid(), networkPath.getFileUrl(), FileSource.jEECG);
            return Result.OK("上传文件成功");
        }
    }

    @AutoLog(value = "文件目录-编辑名称或移动目录")
    @ApiOperation(value = "文件目录-编辑名称或移动目录", notes = "文件目录-编辑名称或移动目录")
    @RequiresPermissions("network:network_path:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody NetworkPath networkPath) {
        NetworkPath path = networkPathService.getById(networkPath.getId());
        //如果修改了目录类型,报错
        if (!path.getType().equals(networkPath.getType())) {
            return Result.error("不允许修改目录类型");
        }
        if (!path.getName().equals(networkPath.getName())) {
            networkService.rename(networkPath.getId(), networkPath.getName());
            return Result.OK("修改名称成功");
        } else if (!path.getPid().equals(networkPath.getPid())) {
            networkService.move(networkPath.getId(), networkPath.getPid());
            return Result.OK("移动目录成功");
        } else {
            return Result.OK("未做任何修改");
        }
    }

    @AutoLog(value = "文件目录-移动文件或文件夹")
//    @ApiOperation(value = "文件目录-移动文件或文件夹", notes = "文件目录-移动文件或文件夹")
    @RequiresPermissions("network:network_path:move")
    @RequestMapping(value = "/move", method = {RequestMethod.PUT})
    public Result<String> move(@RequestParam(name = "id") String id, @RequestParam(name = "pid") String pid) {
        networkService.move(id, pid);
        return Result.OK("移动成功");
    }

    @AutoLog(value = "文件目录-通过id删除")
    @ApiOperation(value = "文件目录-通过id删除", notes = "文件目录-通过id删除")
    @RequiresPermissions("network:network_path:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        networkService.delete(id);
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "文件目录-批量删除")
    @ApiOperation(value = "文件目录-批量删除", notes = "文件目录-批量删除")
    @RequiresPermissions("network:network_path:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        for (String id : ids.split(",")) {
            networkService.delete(id);
        }
        return Result.OK("批量删除成功！");
    }

    //@AutoLog(value = "文件目录-通过id查询")
    @ApiOperation(value = "文件目录-通过id查询", notes = "文件目录-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<NetworkPath> queryById(@RequestParam(name = "id", required = true) String id) {
        NetworkPath networkPath = networkPathService.getById(id);
        if (networkPath == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(networkPath);
    }

    @RequiresPermissions("network:network_path:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, NetworkPath networkPath) {
        return super.exportXls(request, networkPath, NetworkPath.class, "文件目录");
    }

    @RequiresPermissions("network:network_path:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, NetworkPath.class);
    }

}
